<template>
  <PageContainer>
    <view class="container pb-30">
      <Header :title="getPagesTitle" />
      <!-- 供需状态 -->
      <StatusView :bo-status="data?.boStatus" :review-content="data?.reviewContent" />
      <view
        class="mb-12"
        v-if="
          data?.boStatus === BoStatusEnum.Active ||
          data?.boStatus === BoStatusEnum.Closed ||
          data?.boStatus === BoStatusEnum.Expired
        "
      >
        <QuantityStatistics :data="data"></QuantityStatistics>
      </view>

      <DetailsView :data="data" :hide-statistics="true" />
      <view v-if="data" class="mt-12">
        <PersonnelInfo
          :avatar="data.avatar"
          :company-name="data.companyName"
          :company-position="data.companyPosition"
          :user-name="data.userName"
          :member-level-name="data.memberLevelName"
          :org-name="data.orgName"
          :phone-number="data.phone"
        />
      </view>
      <view v-if="data" class="mt-12">
        <SelectedAnswers
          :id="data?.id"
          :manage="true"
          :title="data.title"
          :bo-type="data.boType"
          :is-valid="data.boStatus === BoStatusEnum.Active"
        />
      </view>
      <!-- 正常状态 -->
      <TButtonGroup v-if="data?.boStatus === BoStatusEnum.Active" :show-background="true">
        <template #header>
          <view class="disFlxAC mr-16" style="gap: 16rpx">
            <view v-if="data.editAuth" class="disFlxCC w-50" @click="toEdit">
              <text class="ali-icon fz-24 mb-4">&#xe687;</text>
              <text class="fz-10">修改</text>
            </view>
            <view v-if="!data.editAuth" class="disFlxCC w-50" @click="handleBehaviorCollectOperate">
              <text v-if="data.collect" class="ali-icon fz-24 mb-4" style="color: #2878ff">
                &#xe669;
              </text>
              <text v-else class="ali-icon fz-24 mb-4">&#xe664;</text>
              <text class="fz-10">收藏</text>
            </view>
            <view class="disFlxCC w-50" @click="showSharePopup = true">
              <text class="ali-icon fz-24 mb-4">&#xe6ce;</text>
              <text class="fz-10">分享</text>
            </view>
          </view>
        </template>
        <TButton
          :text="`合作意向(${data?.cooperationNum})`"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toIntentionCooperation"
        />
      </TButtonGroup>
      <!-- 失效/关闭 状态 -->
      <TButtonGroup
        v-else-if="
          data?.boStatus === BoStatusEnum.Closed || data?.boStatus === BoStatusEnum.Expired
        "
        :show-background="true"
      >
        <TButton
          :text="`合作意向(${data?.cooperationNum})`"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toIntentionCooperation"
        />
      </TButtonGroup>
      <!-- 审核失败 -->
      <TButtonGroup
        v-else-if="data?.boStatus === BoStatusEnum.ReviewFailed"
        :show-background="true"
      >
        <TButton
          text="修改内容重新发布"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          :custom-style="{
            backgroundColor: '#F2F3F5',
            color: '#333',
          }"
          @click="toEdit"
        />
      </TButtonGroup>
      <!-- 草稿 -->
      <TButtonGroup v-else-if="data?.boStatus === BoStatusEnum.Draft" :show-background="true">
        <TButton
          text="继续编辑"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toEdit"
        />
      </TButtonGroup>
      <!-- 审核中 -->
      <TButtonGroup v-else-if="data?.boStatus === BoStatusEnum.Reviewing" :show-background="true">
        <TButton
          text="邀请秘书处审核"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          open-type="share"
        />
      </TButtonGroup>
    </view>
  </PageContainer>

  <CustomShare
    v-if="data?.boStatus === BoStatusEnum.Active"
    v-model:visible="showSharePopup"
    @register="handleCustomShareregister"
  />
</template>

<script lang="ts" setup>
  /*  供需详情 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import StatusView from './components/StatusView.vue';
  import DetailsView from '../components/DetailsView.vue';
  import PersonnelInfo from '../components/PersonnelInfo.vue';
  import SelectedAnswers from '../supplyDemandDetails/components/SelectedAnswers.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { getUrl, navigateTo, onLoad } from '@/router';
  import { computed, ref, watchEffect } from 'vue';
  import { BoStatusEnum, BoTypeEnum, ReleaseTypeEnum } from '@/enums/businessOpportunitiesEnum';
  import { boInfoDetail } from '@/api/businessOpportunities';
  import type { ISupplyDemandDetailsResult } from '@/api/businessOpportunities/type';
  import {
    onPullDownRefresh,
  } from '@dcloudio/uni-app';
  import QuantityStatistics from './components/QuantityStatistics.vue';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { getSupplyDemandPosterData, getSupplyDemandWxShareData } from '../components/utils';
  import { addAppShareLog, behaviorCollectOperate } from '@/api';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { BehaviorCollectTypeEnum } from '@/enums/publicModuleEnum';
  import { Toast } from '@/utils';

  const { setWxSharePath, createShareQuery, setWxShareTimelineQuery } = useAppShare();
  /** 分享弹窗 */
  const showSharePopup = ref(false);
  const customShareLoading = ref(false);
  function handleCustomShareregister(e: any) {
    register(e);
    customShareLoading.value = true;
  }

  const [
    register,
    {
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setShareTimelineContent,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      timeline: false,
      copyLink: true,
      insertOffiaccount: true,
      offiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  const data = ref<ISupplyDemandDetailsResult>();

  const id = ref();
  const releaseType = ref<ReleaseTypeEnum>();
  onLoad<'businessOpportunitieDetail'>((op) => {
    releaseType.value = op.releaseType;
    id.value = op.id;
    getData();
  });

  const stopWatch = watchEffect(async () => {
    const v1 = customShareLoading.value;
    const v2 = data.value;
    if (!v1 || !v2) return;
    setInternalLinkOptions({
      name: 'supplyDemandDetails',
      options: { id: data.value!.id },
    });
    const path = setWxSharePath({
      name: 'supplyDemandDetails',
      options: { id: data.value!.id },
    });

    const routeQuery = createShareQuery({ id: data.value!.id });
    await setWxShareOptions([getSupplyDemandWxShareData(data.value!, path)]);
    const { id: shareLogId } = await addAppShareLog({
      path: getUrl('supplyDemandDetails'),
      query: JSON.stringify(routeQuery),
    });
    setShareLogId(shareLogId);
    const shareTimelineContent = {
      query: setWxShareTimelineQuery(routeQuery),
      title: data.value?.title,
      imageUrl: 'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/bo-icon.jpg',
    };
    setShareTimelineContent(shareTimelineContent);

    const codeImg = await createMiniCode({ shareLogId });
    const posterData = getSupplyDemandPosterData(data.value!, codeImg);
    await setPosterDrawData([posterData]);

    stopWatch();
  });

  const getPagesTitle = computed(() => {
    if (!data.value) return '详情';
    return data.value.boType === BoTypeEnum.Demand ? '需求详情' : '供应详情';
  });

  async function getData() {
    const res = await boInfoDetail(id.value, releaseType.value);
    if (res.boStatus !== BoStatusEnum.Active) {
      wx.hideShareMenu();
    }
    data.value = res;
    uni.stopPullDownRefresh();
  }

  const toEdit = () => {
    navigateTo({
      name: 'releaseBusinessOpportunities',
      options: {
        id: data.value?.id,
        releaseType: releaseType.value!,
        success: () => getData()
      },
    });
  };

  const toIntentionCooperation = () => {
    if (data.value) {
      navigateTo({
        name: 'intentionCooperation',
        options: {
          id: data.value?.id,
          type: 'list',
          boType: data.value?.boType,
          title: data.value?.title,
        },
      });
    }
  };

  function handleBehaviorCollectOperate() {
    behaviorCollectOperate({ type: BehaviorCollectTypeEnum.BO, dataId: data.value?.id! }).then(
      (bol) => {
        Toast('收藏成功');
        data.value!.collect = bol;
      },
    );
  }

  // onShareAppMessage(() => {
  //   if (data.value?.boStatus === BoStatusEnum.Reviewing) {
  //     return {
  //       title: `${userInfo.userName}正在申请供需发布，秘书处管理员快来帮我审核吧~`,
  //       path: setWxSharePath({ name: 'businessOpportunitieAuditDetail', options: {  } }),
  //       imageUrl:
  //         'https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/Invitation-handling.png',
  //     };
  //   }
  //   return {};
  // });
  onPullDownRefresh(() => {
    getData();
  });
</script>

<style lang="scss" scoped>
  .footer-placeholder {
    height: 188rpx;
  }

  .footer {
    width: 100%;
    height: 128rpx;
    position: fixed;
    left: 0;
    bottom: 0;
    background-color: #fff;
    box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.16);
  }
</style>
